// 页面加载完成后获取日期列表
document.addEventListener('DOMContentLoaded', async () => {
    try {
        const response = await fetch('/api/v1/dates');
        if (!response.ok) {
            throw new Error('获取日期列表失败');
        }
        const responseData = await response.json();
        const dates = responseData.data.dates;
        const dateList = document.getElementById('date-list');
        dates.forEach(date => {
            const dateItem = document.createElement('div');
            dateItem.className = 'date-item p-2 rounded hover:bg-gray-100 cursor-pointer';
            dateItem.dataset.date = date;
            dateItem.textContent = date;
            dateItem.addEventListener('click', async () => {
                try {
                    await handleDateSelection(date, dates);
                } catch (error) {
                    console.error('加载板块数据出错:', error);
                    alert('加载板块数据出错，请稍后重试');
                }
            });
            dateList.appendChild(dateItem);
        });

        // 加载默认日期数据
        if (dates.length > 0) {
            const defaultDate = dates[0];
            await handleDateSelection(defaultDate, dates);
        }
    } catch (error) {
        console.error('加载日期列表出错:', error);
        alert('加载日期列表出错，请稍后重试');
    }
});

// 更新所有表格内容
function updateAllTables(data) {

    const d = data.data
    // 区域1: 长期低迷及轮动排除剔除
    updateTable('eliminated-plates-1', d.eliminated_plates_1);
    updateTable('reserved-plates-1', d.reserved_plates_1);
    
    // 区域2: 昨日TOP20板块差异化处理
    updateTable('eliminated-plates-2', d.eliminated_plates_2);
    updateTable('reserved-plates-2', d.reserved_plates_2);
    
    // 区域3: 推荐
    updateTable('all-non-eliminated-plates', d.all_reserved_plates);
    updateTable('top-recommended-plates', d.top_recommended_plates);

    // 区域4: 命中
    updateTable('yesterday-hit-plates', d.yesterday_hit_plates);
    updateTable('today-top-gain-plates', d.today_top_gain_plates);
}

// 更新单个表格内容
function updateTable(tableId, tableData) {
    const table = document.getElementById(tableId);
    const tbody = table.querySelector('tbody');
    tbody.innerHTML = '';
    
    if (tableData && Array.isArray(tableData)) {
        tableData.forEach((item, index) => {
            const row = document.createElement('tr');
            const indexCell = document.createElement('td');
            indexCell.className = 'px-4 py-2 border';
            indexCell.textContent = index + 1;
            row.appendChild(indexCell);
            Object.entries(item).forEach(([key, value], cellIndex) => {
                const cell = document.createElement('td');
                cell.className = 'px-4 py-2 border';
                
                cell.textContent = value 
                if (key === "daily_gain") {
                    cell.textContent = value + '%'
                }
                
                row.appendChild(cell);
                if (tableId === 'yesterday-hit-plates' || tableId == 'today-top-gain-plates') {
                    if (value === '已命中') {
                        row.classList.add('bg-green-100');
                    }
                }
            });
            tbody.appendChild(row);
        });
    }
}

async function handleDateSelection(date, dates) {
    // 移除所有日期项的选中样式
    document.querySelectorAll('.date-item').forEach(item => {
        item.classList.remove('bg-gray-200');
    });
    // 添加当前日期项的选中样式
    document.querySelectorAll('.date-item').forEach(item => {
        if (item.dataset.date === date) {
            item.classList.add('bg-gray-200');
            document.getElementById('selected-date').textContent = `（${date}）`;
        }
    });
    // 获取当前日期在日期列表中的索引
    const dateIndex = dates.indexOf(date);
    // 获取前一天的日期，如果当前是第一个日期，则不显示命中率，注意，这里日期是倒序的
    const prevDate = dateIndex < dates.length - 1 ? dates[dateIndex + 1] : null;
    if (prevDate) {
        // 获取并显示前一天的命中率
        const hitRateResponse = await fetch(`/api/v1/hit-rate?date=${prevDate}`);
        document.getElementById('prev-trading-date').textContent = prevDate;
        if (hitRateResponse.ok) {
            const hitRateData = await hitRateResponse.json();
            if (hitRateData.code === 200) {
                document.getElementById('hit-rate').textContent = ` 命中率: ${(hitRateData.data.hit_rate * 100).toFixed(2)}%`;
            } else {
                document.getElementById('hit-rate').textContent = '';
            }
        }
    } else {
        document.getElementById('hit-rate').textContent = '';
    }
    const plateDataResponse = await fetch(`/api/v1/plate-data?date=${date}`);
    if (!plateDataResponse.ok) {
        throw new Error('获取板块数据失败');
    }
    const plateData = await plateDataResponse.json();
    updateAllTables(plateData);
}